<script setup lang="ts">
import { computed, reactive, ref, watch, watchEffect } from 'vue';
import { localStg } from '@/utils/storage';
import { deleteCustomBackgroundApi } from '@/service/api';
import { useStore } from '../../store';
const { VITE_UPLOAD_PATH } = import.meta.env;
const store = useStore();

const bgCategoryName = ['默认', '教育', '科技', '医疗', '直播'];
const tabValue = ref(bgCategoryName[0]);
const tabIndex = computed(() => {
  return bgCategoryName.indexOf(tabValue.value);
});
const direction = computed(() => {
  return store.canvasConfig.direction;
});

// 列表拆成两个
const bgList = computed(() => {
  const type = direction.value === 'vertical' ? 0 : 1;
  const images = (store.getDict('bg') && store.getDict('bg').filter((item: any) => item.imageType === 0)) || [];
  const result = images.filter((item: any) => item.imgStyle === type) || [];
  return result.filter((item: any) => item.imgCategory === tabIndex.value);
});
const getDefalutBg = () => {
  const type = direction.value === 'vertical' ? 0 : 1;
  const images = (store.getDict('bg') && store.getDict('bg').filter((item: any) => item.imageType === 0)) || [];
  const result = images.filter((item: any) => item.imgStyle === type) || [];
  const defaultBgList = result.filter((item: any) => item.imgCategory === 0);
  return defaultBgList[0];
};
const bgListCategory: any = computed(() => {
  if (!bgList.value) return [];
  const data = _groupByCategory(bgList.value);
  return Object.values(data).sort((a: any, b: any) => a[0].imgCategory - b[0].imgCategory);
});

const bgCustomList = computed(() => {
  const images = (store.getDict('bg') && store.getDict('bg').filter((item: any) => item.imageType === 1)) || [];
  return images.filter((item: any) => item.imgCategory === tabIndex.value);
});
watch(bgCustomList, () => {
  console.log(JSON.stringify(bgCustomList.value), 'bgList');
});

// eslint-disable-next-line no-underscore-dangle
function _groupByCategory(items: any[]) {
  return items.reduce((groups, item) => {
    // 检查 groups 对象中是否已经有了当前 riskLevel 的数组
    // 如果没有，就创建一个新数组
    if (item.imgCategory === null || item.imgCategory === undefined) return groups;
    // eslint-disable-next-line no-multi-assign
    const group = (groups[item.imgCategory] ||= []);
    // 将当前项添加到对应的数组中
    group.push(item);
    return groups;
  }, {}); // 初始化 groups 为一个空对象
}

// 当前激活tab
const currentTab = computed(() => {
  return store.bgTab;
});
function handleSelectTab(value: number) {
  store.updateBgTab(value);
}

// 图片上传
const upload = reactive<any>({
  loading: false,
  currentTab: '',
  accept: 'image/jpeg, image/png, image/gif',
  headers: {
    authorization: `${localStg.get('humanToken')}`
  },
  finish: async ({ event }: { event?: ProgressEvent }) => {
    const { data } = JSON.parse((event?.target as XMLHttpRequest).response);
    if (data && data.url) {
      window.$message?.success('上传成功');
      await store.init('bg'); // 更新字典

      // 下面咏梅的 1. 通用上传 | 2.接口提交
      // const params = {
      //   account: localStg.get('userId'),
      //   url: data.url,
      //   imageType: 1,
      //   imgCategory: 0
      // };
      // const { data: result } = await createCustomBackgroundApi(params);
      // if (result) {
      //   window.$message?.success('上传成功');
      //   store.init(); // 更新字典
      //   // store.updateBgDictList(data.url); // 前端写入 废弃
      // } else {
      //   window.$message?.error('图片上传错误');
      // }
    } else {
      window.$message?.error('图片上传错误');
    }
    upload.loading = false;
  },
  error: () => {
    window.$message?.error('背景上传错误');
    // 防闪
    setTimeout(() => {
      upload.loading = false;
    }, 1000);
  },
  before: (_file: File) => {
    upload.loading = true;
    upload.currentTab = `${currentTab.value}_${tabValue.value}`;
  }
});

const showLoadingTabItem = computed(() => {
  return upload.currentTab === `${currentTab.value}_${tabValue.value}`;
});

function handleSelect(row: any) {
  store.updateBg(row);
}

// 删除已经上传的图片
async function deleteCustomBg(row: any, event?: MouseEvent | TouchEvent) {
  event?.stopPropagation();
  const { data } = await deleteCustomBackgroundApi(row.id);
  if (data) {
    window.$message?.success('删除成功');
    store.deleteBgDictItem(row.id); // 或者 store.init 更新列表
  }
  // 如果是已渲染背景，切换
  if (store.bg.id === row.id) store.updateBg(getDefalutBg());
}

// 默认选择列表第一个
watch(
  () => store.getDict('bg'),
  value => {
    const { id, url } = store.bg;
    const defaultBg = bgListCategory.value[0]?.[0];
    console.log(defaultBg, 'defaultBg');
    store.updateDefault(defaultBg, 'bg');
    if (!id && !url && value.length) store.updateBg(defaultBg);
  }
);
watch(
  () => store.canvasConfig.size,
  value => {
    if (store.isGetDraftData) return;
    const bgListStore = store.getDict('bg') || [];
    const size = store.canvasConfig.size;
    console.log(size);
    // const { id, url } = store.bg;
    const defaultBg = bgListCategory.value[0]?.[0];
    console.log(defaultBg, 'defaultBg');
    store.updateDefault(defaultBg, 'bg');
    if (bgListStore.length) store.updateBg(defaultBg);
  }
);

const getThumbnailImg = (url: string) => {
  // http://49.235.128.65:9000/digitalman-platform/60a63374c169260dde674a8458cab2fe.jpg 转化为缩略图
  // http://49.235.128.65:9000/digitalman-platform/60a63374c169260dde674a8458cab2fe_thumbnail.jpg
  return url.replace(/(\.\w+)$/, '_thumbnail$1');
};
</script>

<template>
  <div id="bg-list" class="list">
    <div class="list-head p-4 pt-6">
      <span :class="{ active: currentTab === 1 }" class="mr-6" @click="handleSelectTab(1)">系统背景</span>
      <span :class="{ active: currentTab === 2 }" @click="handleSelectTab(2)">自定义</span>
    </div>
    <NScrollbar class="list-main">
      <NTabs v-model:value="tabValue" class="px-4" type="segment" animated>
        <NTabPane
          v-for="(item, index) in bgCategoryName"
          v-show="currentTab === 1"
          :key="index"
          :name="item"
          :tab="item"
        ></NTabPane>
      </NTabs>

      <ul v-if="currentTab === 1" class="animate-fade-in animate-duration-200 select-none p-4">
        <li
          v-for="item in bgList"
          :key="item.id"
          :class="{ active: store.getBgId() === item.id }"
          class="item-card square flex-center"
          @click="handleSelect(item)"
        >
          <NImage preview-disabled lazy class="object-contain" :src="item.thumbnailUrl" />
        </li>
      </ul>

      <ul v-if="currentTab === 2" class="animate-fade-in animate-duration-200 p-4">
        <li class="grid-col-[1/-1]">
          <NUpload
            :accept="upload.accept"
            :headers="upload.headers"
            :on-finish="upload.finish"
            :on-error="upload.error"
            :loading="upload.loading"
            :data="{
              imageType: '1',
              imgCategory: tabIndex.toString()
            }"
            :action="VITE_UPLOAD_PATH"
            @before-upload="upload.before"
          >
            <div class="mt-4 h-11 w-72 flex-center cursor-pointer rounded-2 bg-content_hover text-base_text">
              <SvgIcon class="mr-2 text-6" icon="ic:round-add"></SvgIcon>
              本地上传
            </div>
          </NUpload>
          <p class="mt-2 text-center text-base_text/25">支持JPG、PNG、GIF格式</p>
        </li>
        <li
          v-if="upload.loading && showLoadingTabItem"
          class="item-card square flex-center animate-fade-in animate-duration-100"
        >
          <NSpin size="large" />
        </li>
        <li
          v-for="(item, index) in bgCustomList"
          :key="item.thumbnailUrl + '|' + index"
          :class="{ active: store.getBgId() === item.id }"
          class="item-card square flex-center"
        >
          <img class="object-contain" :src="item.thumbnailUrl" @click.stop="handleSelect(item)" />
          <!-- 下拉删除 -->
          <NPopconfirm class="!bg-header" :show-icon="false" @positive-click="deleteCustomBg(item, $event)">
            <template #trigger>
              <NButton type="default" class="absolute right-2 top-2 z-99 h-6 p-1">
                <SvgIcon icon="clarity:trash-line" class="text-4"></SvgIcon>
              </NButton>
            </template>
            确定删除此背景？
          </NPopconfirm>
        </li>
      </ul>
    </NScrollbar>
  </div>
</template>

<style scoped lang="scss">
#bg-list {
  .list-head {
    > span {
      @apply relative text-light_text cursor-pointer transition-all leading-none;

      &:after {
        content: '';
        @apply transition-all transition-duration-400 bg-transparent w-[80%] h-0.5 absolute left-[10%] -bottom-4;
      }
    }

    .active {
      position: relative;
      @apply text-base_text;

      &:after {
        @apply bg-primary;
      }
    }
  }
}

:deep(.n-upload-file-list) {
  display: none;
}
</style>
